<template>
  <div class="searchbox">
    <el-row>
      <el-col :span="24">
        <el-autocomplete
          class="keyword"
          v-model="keyword"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入商品关键字"
          @select="handleSelect"
        ></el-autocomplete>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col v-for="item in hotkeys" :key="item" :span="3">
        <router-link :to="{ path:'/searchdetail',query:{'keyword':item} }">{{item}}</router-link>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { searchGood, getHotKey } from "../api/requestapi";
export default {
  name: "Search",

  data() {
    return {
      // 关键词都返回结果
      result: [],
      // 填入的搜索关键词
      keyword: "",
      timeout: null,
      // 热门关键词的集合
      hotkeys: [],
    };
  },

  created() {
    getHotKey().then((res) => {
      console.log("热门搜索");
      console.log(res.data);
      this.hotkeys = res.data;
    });
  },

  methods: {
    querySearchAsync(queryString, cb) {
      //清空搜索建议
      this.result = [];

      if (queryString === "") {
        cb(this.result);
        return;
      }

      //发送搜索请求
      searchGood(queryString).then((Response) => {
        this.result = Response.data;
        cb(this.result);
      });
    },

    handleSelect(item) {
      console.log(item.value);
      //跳转搜索页面
      this.$router.push({
        path: "/searchdetail",
        query: { keyword: item.value },
      });
    },
    //跳转进行搜索
    search() {
      this.$router.push({
        path: "/searchdetail",
        query: { keyword: this.keyword },
      });
    },
  },
};
</script>

<style>
.searchbox {
  width: 800px;
  height: 80px;
  margin: 0 auto;
}

.search {
  height: 200px;
  display: block;
}
.keyword {
  width: 700px;
}
</style>